package com.emapp.lccode.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

/**
 *@Description: TODO
 *@Author:  zhang
 *@Date:   2023/6/20
 */
class PeriodicTask(private val delaMillis: Long, private val task: () -> Unit) {
    private var job: Job? = null
    fun start() {
        job?.cancel()
        job = CoroutineScope(Dispatchers.Default).launch {
            while (isActive) {
                task()
                delay(delaMillis)
            }
        }
    }

    fun stop() {
        job?.cancel()
        job = null
    }
}